<?php
/**
 * Created by PhpStorm.
 * User: zhanglei
 * Date: 2018/5/10
 * Time: 16:49
 */

namespace app\admin\model;


class Order extends BaseModel
{
    /**
     * 一对多关联order_detail表，订单具体内容
     */
    public function detail()
    {
        return $this->hasMany('OrderDetail','order_id','id');
    }

    /**
     * 反向关联用户表，获取在此订单里的用户信息
     */
    public function user()
    {
        return $this->belongsTo('User', 'user_id', 'id');
    }
    /**
     * 反向关联优惠券表获取在此订单内获取使用的优惠券
     */
    public function coupon()
    {
        return $this->belongsTo('CouponCategory', 'coupon_id', 'id');
    }
    /**
     * 关联地址表
     */
    public function address()
    {
        return $this->belongsTo('Address','address_id','id');
    }

    //对超时的订单用户没有确认收获的自动确认收获
    public static function autoConfirmOrder()
    {
        $orders = self::field('id,create_time')->where(['status'=>3])->select();
        foreach($orders as $k=>$v){
            $create_time = strtotime($v->getData('create_time'));
            $now = time();
            if(($now - $create_time) > (config('setting.auto_confirm_time') * 24 * 60 * 60)){
                $id = $v->getData('id');
                self::where(['id'=>$id])->update(['status'=>4]);
            }
        }
    }

    //订单的失效时间
    public static function abateOrder($arr,$time)
    {
        $orders = self::field('id,create_time')->where($arr)->select();
        $now = time();
        foreach($orders as $k=>$v){
            $create_time = strtotime($v->getData('create_time'));
            if(($now - $create_time) > $time){
                $id = $v->getData('id');
                self::where(['id'=>$id])->update(['status'=>8]);
            }
        }
    }
}